﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections;
using System.IO;

namespace StationUpdate
{
    public class IniOperate
    {
        public IniOperate()
        {

        }

        #region 读写INI文件
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="iniFilePath">文件路径</param> 
        /// <param name="Section">键</param> 
        /// <param name="IniKey">值</param>
        /// <returns></returns>
        public static string IniValue(string iniFilePath, string Section, string IniKey)
        {
            if (System.IO.File.Exists(iniFilePath))
            {
                System.IO.File.GetAccessControl(iniFilePath);
                StringBuilder temp = new StringBuilder(500);
                try
                {
                    GetPrivateProfileString(Section, IniKey, "", temp, 500, iniFilePath);
                }
#pragma warning disable CS0168 // 声明了变量“ex”，但从未使用过
                catch (Exception ex)
#pragma warning restore CS0168 // 声明了变量“ex”，但从未使用过
                {
                    return string.Empty;
                }
                return temp.ToString();
            }
            else
            {
                return string.Empty;
            }
        }
        /// <summary> 
        /// 写入INI文件 
        /// </summary> 
        /// <param name="iniFilePath">文件路径</param> 
        /// <param name="Section">项目名称(如 [TypeName] )</param> 
        /// <param name="Key">键</param> 
        /// <param name="Value">值</param> 
        public static void IniWriteValue(string iniFilePath, string Section, string Key, string Value)
        {
            if (!System.IO.File.Exists(iniFilePath))
            {
                try
                {
                    FileStream myFs = new FileStream(iniFilePath, FileMode.Create);
                    myFs.Close();
                    myFs.Dispose();
                }
                catch (Exception)
                {
                    throw;
                }

            }
            while (true)
            {
                try
                {
                    WritePrivateProfileString(Section, Key, Value, iniFilePath);
                }
                catch
                {
                    System.Threading.Thread.Sleep(50);
                    return;
                }
                return;
            }

        }
        #endregion

    }
}
